import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:bot_toast/bot_toast.dart';

import '../controllers/mine_controller.dart';
import '../../../widgets/safe_network_image.dart';

class MineView extends GetView<MineController> {
  const MineView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFEDF3FA),
      body: Stack(
        children: [
          // 顶部背景图
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            child: Image.asset(
              'assets/images/mine/top_bg.png',
              width: 750.w,
              height: 453.h,
              fit: BoxFit.cover,
            ),
          ),
          // 主要内容
          SafeArea(
            child: SingleChildScrollView(
              child: Column(
                children: [
                  // 个人信息区域
                  Padding(
                    padding: EdgeInsets.only(
                      left: 40.w,
                      right: 40.w,
                      top: 60.h,
                    ),
                    child: Material(
                      color: Colors.transparent,
                      child: InkWell(
                        onTap: () async {
                          await Get.toNamed('/setting');
                          // 从设置页面返回后，重新获取用户信息
                          controller.getUserInfo();
                        },
                        borderRadius: BorderRadius.circular(12.r),
                        child: Container(
                          padding: EdgeInsets.symmetric(vertical: 20.h),
                          child: Row(
                            children: [
                              // 用户头像
                              Obx(
                                () => ClipOval(
                                  child: SafeNetworkImage(
                                    imageUrl: controller.avatarUrl,
                                    width: 110.w,
                                    height: 110.h,
                                    fit: BoxFit.cover,
                                    borderRadius: BorderRadius.circular(55.w),
                                    errorWidget: Image.asset(
                                      'assets/images/default_avatar.png',
                                      width: 110.w,
                                      height: 110.h,
                                      fit: BoxFit.cover,
                                    ),
                                  ),
                                ),
                              ),
                              SizedBox(width: 20.w),
                              // 用户名
                              Expanded(
                                child: Obx(
                                  () => Text(
                                    controller.userName ?? '用户',
                                    style: TextStyle(
                                      fontSize: 38.sp,
                                      fontFamily: 'Source Han Sans',
                                      color: const Color(0xFF333333),
                                      fontWeight: FontWeight.w500,
                                    ),
                                  ),
                                ),
                              ),
                              // 右箭头
                              Icon(
                                Icons.keyboard_arrow_right,
                                color: const Color(0xFFA2A2A2),
                                size: 48.sp,
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                  SizedBox(height: 57.h),
                  // 功能区域容器
                  Container(
                    margin: EdgeInsets.symmetric(horizontal: 20.w),
                    decoration: BoxDecoration(
                      image: const DecorationImage(
                        image: AssetImage('assets/images/mine/main_bg.png'),
                        fit: BoxFit.cover,
                      ),
                      borderRadius: BorderRadius.circular(16.r),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 常用功能标题
                        Padding(
                          padding: EdgeInsets.only(
                            left: 30.w,
                            top: 44.h,
                            bottom: 30.h,
                          ),
                          child: Text(
                            '常用功能',
                            style: TextStyle(
                              fontSize: 32.sp,
                              fontFamily: 'Source Han Sans',
                              fontWeight: FontWeight.w500,
                              color: const Color(0xFF333333),
                            ),
                          ),
                        ),

                        // 功能菜单列表
                        _buildMenuItem(
                          icon: 'assets/images/mine/update.png',
                          title: '修改密码',
                          onTap: () {
                            Get.toNamed('/update-pwd');
                          },
                          showDivider: true,
                        ),
                        _buildMenuItem(
                          icon: 'assets/images/mine/service_icon.png',
                          title: '服务协议',
                          onTap: controller.openServiceAgreement,
                          showDivider: true,
                        ),
                        _buildMenuItem(
                          icon: 'assets/images/mine/privacy_icon.png',
                          title: '隐私协议',
                          onTap: controller.openPrivacyAgreement,
                          showDivider: true,
                        ),
                        // _buildMenuItem(
                        //   icon: 'assets/images/mine/settings_icon.png',
                        //   title: '设置中心',
                        //   onTap: () async {
                        //     await Get.toNamed('/setting');
                        //     // 从设置页面返回后，重新获取用户信息
                        //     controller.getUserInfo();
                        //   },
                        //   showDivider: true,
                        // ),
                        Obx(
                          () => _buildMenuItem(
                            icon: 'assets/images/mine/logout_icon.png',
                            title: '退出登录',
                            onTap:
                                controller.isLoading
                                    ? () {}
                                    : () {
                                      _showLogoutDialog();
                                    },
                            showDivider: false,
                          ),
                        ),
                      ],
                    ),
                  ),

                  SizedBox(height: 80.h),
                  // 底部装饰图片
                  Image.asset(
                    'assets/images/mine/bottom_bg.png',
                    width: 578.w,
                    height: 194.h,
                    fit: BoxFit.contain,
                  ),

                  SizedBox(height: 40.h), // 底部安全间距
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 显示退出登录确认弹框
  void _showLogoutDialog() {
    BotToast.showWidget(
      toastBuilder: (cancelFunc) => _LogoutDialog(onCancel: cancelFunc),
    );
  }

  Widget _buildMenuItem({
    required String icon,
    required String title,
    required VoidCallback onTap,
    bool showDivider = true,
  }) {
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(8.r),
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 30.w, vertical: 32.h),
          child: Column(
            children: [
              Row(
                children: [
                  Image.asset(icon, width: 50.w, height: 50.h),
                  SizedBox(width: 20.w),
                  Expanded(
                    child: Text(
                      title,
                      style: TextStyle(
                        fontSize: 26.sp,
                        fontFamily: 'Source Han Sans',
                        color: const Color(0xFF333333),
                      ),
                    ),
                  ),
                  Icon(
                    Icons.keyboard_arrow_right,
                    color: const Color(0xFFA2A2A2),
                    size: 48.sp,
                  ),
                ],
              ),
              SizedBox(height: 21.h),
              if (showDivider) ...[
                Container(
                  height: 0.5.h,
                  color: const Color(0xFFE2E2E2),
                  margin: EdgeInsets.only(left: 70.w),
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }
}

/// 退出登录确认弹框
class _LogoutDialog extends StatefulWidget {
  final VoidCallback? onCancel;

  const _LogoutDialog({this.onCancel});

  @override
  _LogoutDialogState createState() => _LogoutDialogState();
}

class _LogoutDialogState extends State<_LogoutDialog>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _slideAnimation;
  late Animation<double> _fadeAnimation;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 400),
      vsync: this,
    );

    _slideAnimation = Tween<double>(begin: 1.0, end: 0.0).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeOutCubic),
    );

    _fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeIn),
    );

    _animationController.forward();
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.transparent,
      child: AnimatedBuilder(
        animation: _animationController,
        builder: (context, child) {
          return Stack(
            children: [
              // 遮盖层
              Opacity(
                opacity: _fadeAnimation.value * 0.5,
                child: Container(
                  width: double.infinity,
                  height: double.infinity,
                  color: Colors.black,
                ),
              ),
              // 弹出框 - 居中显示
              Center(
                child: Transform.translate(
                  offset: Offset(0, _slideAnimation.value * 200.h),
                  child: Container(
                    width: 536.w,
                    height: 407.h,
                    margin: EdgeInsets.symmetric(horizontal: 20.w), // 防止溢出
                    decoration: BoxDecoration(
                      // 渐变背景
                      gradient: const LinearGradient(
                        begin: Alignment(0.0, -0.95), // 177度角度
                        end: Alignment(0.0, 1.0),
                        stops: [0.08, 1.0],
                        colors: [
                          Color(0xFFD3E9FF), // #D3E9FF 8%
                          Color(0xFFFEFEFF), // #FEFEFF 100%
                        ],
                      ),
                      borderRadius: BorderRadius.circular(30.r),
                    ),
                    child: Stack(
                      children: [
                        // 背景图片
                        Positioned.fill(
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(30.r),
                            child: Image.asset(
                              'assets/images/tanchukuang.png',
                              fit: BoxFit.cover,
                            ),
                          ),
                        ),
                        // 内容
                        Padding(
                          padding: EdgeInsets.symmetric(
                            horizontal: 30.w,
                            vertical: 30.h,
                          ),
                          child: Column(
                            children: [
                              SizedBox(height: 20.h),
                              // 问号图片
                              Image.asset(
                                'assets/images/wenhao.png',
                                width: 80.w,
                                height: 80.h,
                              ),
                              SizedBox(height: 24.h),
                              // 标题
                              Text(
                                '退出登录',
                                style: TextStyle(
                                  fontSize: 32.sp,
                                  fontWeight: FontWeight.w600,
                                  color: const Color(0xFF333333),
                                ),
                              ),
                              SizedBox(height: 16.h),
                              // 内容
                              Text(
                                '你确定要退出登录吗？',
                                style: TextStyle(
                                  fontSize: 28.sp,
                                  color: const Color(0xFF666666),
                                ),
                              ),
                              const Spacer(),
                              // 按钮区域
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: [
                                  // 取消按钮
                                  GestureDetector(
                                    onTap: () {
                                      widget.onCancel?.call();
                                    },
                                    child: Container(
                                      width: 180.w,
                                      height: 70.h,
                                      decoration: BoxDecoration(
                                        color: const Color(
                                          0xFF047FF7,
                                        ), // #047FF7
                                        borderRadius: BorderRadius.circular(
                                          20.r,
                                        ),
                                      ),
                                      child: Center(
                                        child: Text(
                                          '取消',
                                          style: TextStyle(
                                            fontSize: 26.sp,
                                            color: Colors.white,
                                            fontWeight: FontWeight.w500,
                                          ),
                                        ),
                                      ),
                                    ),
                                  ),
                                  GestureDetector(
                                    onTap: () {
                                      widget.onCancel?.call();
                                      final controller =
                                          Get.find<MineController>();
                                      controller.logout();
                                    },
                                    child: Container(
                                      width: 180.w,
                                      height: 70.h,
                                      decoration: BoxDecoration(
                                        color: const Color(
                                          0xFFDEEDFF,
                                        ), // #DEEDFF
                                        borderRadius: BorderRadius.circular(
                                          20.r,
                                        ),
                                        border: Border.all(
                                          color: const Color(
                                            0xFF79B4F9,
                                          ), // #79B4F9
                                          width: 1.w,
                                        ),
                                      ),
                                      child: Center(
                                        child: Text(
                                          '确认',
                                          style: TextStyle(
                                            fontSize: 26.sp,
                                            color: const Color(0xFF047FF7),
                                            fontWeight: FontWeight.w500,
                                          ),
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                              SizedBox(height: 20.h),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          );
        },
      ),
    );
  }
}
